<?php
/**
 * Created by b17
 * 2/27/12 8:12 PM
 */

use Managers\Text\Filter\StopWordFilter;

class AdController extends G4T_Controller
{
    const ITEMS_PER_PAGE = 10;

    private $_user;


    public function init()
    {
        parent::init();
        $this->_user = \Zend_Auth::getInstance()->getStorage()->read();
    }

    public function indexAction()
    {
        $categoryManager = new \Managers\Category();
        $categories = $categoryManager->getListWithChildren();
        $this->view->categories = $categories;
    }

    public function viewAction()
    {
        $subcatManager = new \Managers\SubCategory();
        $category = $subcatManager->getById($this->_getParam('id'));
        $this->view->category = $category;

        if (!$category) {
            $this->_flashMessenger->addMessage('Category not found.', Lib_Flash::ERROR, Lib_Flash::LATER);
            $this->_redirect('/ad');
        }

        $adBuilder = new \Managers\Builder\AdBuilder();
        $adBuilder->setSubCategory($this->_getParam('id'))
            ->addOrderByPromotedDate()
            ->addOrderById();

        $page = (int)$this->_getParam('page');
        $offset = $page > 0 ? ($page - 1) * self::ITEMS_PER_PAGE : 0;
        $total = $adBuilder->getTotal();
        $this->view->total = $total;

        $adBuilder->setLimit(self::ITEMS_PER_PAGE, $offset);
        $ads = $adBuilder->getList();
        $this->view->ads = $ads;

        $this->displayPaginantor($total, $page, self::ITEMS_PER_PAGE);
    }

    public function listAction()
    {
        $categoryManager = new \Managers\Category();
        $categories = $categoryManager->getList();

        $this->view->categories = $categories;
    }


    public function addAction()
    {
        $categoryId = $this->_getParam('id');
        $categoryManager = new \Managers\Category();
        $category = $categoryManager->getById($categoryId);
        $this->view->category = $category;
        if (!$category) {
            $this->_flashMessenger->addMessage('Категория не найдена.', Lib_Flash::ERROR, Lib_Flash::LATER);
            $this->_redirect('/ad');
        }

        $form = $this->_getAddForm($categoryId);
        $this->view->form = $form;

        if ($this->_request->isPost()) {
            if ($form->isValid($this->_getAllParams())) {
                $values = $form->getValues();

                $filter = new StopWordFilter();
                foreach ($values as &$value) {
                    $value = $filter->sanitize($value);
                }

                if (!$filter->hasErrors()) {
                    $adManager = new \Managers\Ad();
                    $ad = $adManager->create($values, $this->_user);
                    $this->_flashMessenger->addMessage('Ваше объявление добавлено.', Lib_Flash::NOTICE, Lib_Flash::LATER);
                    $this->_redirect("/ad/view/id/{$ad->getSubCat()->getId()}");
                } else {
                    $form->populate($values);
                    $foundWords = $filter->getFoundWords();
                    $this->_flashMessenger->addMessage(sprintf("Слова: %s - недопустимы.", join(',', $foundWords)),
                        Lib_Flash::ERROR, Lib_Flash::NOW);
                }
            }
        }
    }

    private function _getAddForm($categoryId)
    {
        $formBuilder = \G4T\Form\FormBuilder::createFormBuilder(\Managers\Ad::TABLE)
            ->addField('token', 'hash');

        if (empty($this->_user)) {
            $formBuilder
                ->addField('author', 'string', array('label' => 'Имя'))
                ->addField('email', 'email', array('label' => 'Email'));
        }

        $subcatManager = new \Managers\SubCategory();
        $subcats = $subcatManager->getByCategory($categoryId);
        $list = $subcatManager->getSelectList($subcats);
        $formBuilder
            ->addField('phone', 'phone', array('label' => 'Телефон'))
            ->addField('subCat', 'select', array('label' => 'Куда добавить', 'values' => $list))
            ->addField('content', 'text', array('label' => 'Текст объявления', 'rows' => '6', 'style' => 'width:97%'))
            ->addField('submit', 'submit', array('label' => "Добавить", 'class' => 'btn'));
        return $formBuilder->getForm();

    }

}
